var app = getApp();
var ajax = require('../../utils/ajax.js');
var util = require('../../utils/util.js');
var wxUtil = require('../../utils/wxUtil.js');
var shopInfo = require('../../components/shopInfo/index.js');
var MPage = require('../MPage.js');
var begin_time = "";
var end_time = "";
var sliderWidth = 128; // 需要设置slider的宽度，用于计算中间位置
var common = require('../../utils/common.js');

Page(common.extendPage(MPage, {
    data: {
        shop: {},
        address: {},
        goodsList: [],
        orderAmount: 0,
        orderType: '',
        noAddr: false,
        goodsId: '',
        addressId: '',
        orderId: '',
        wxPayParams: '',
        wxPaySucUrl: '',
        dataLoaded: false,
        loading: false,
        moreLoading: false,
        coupon: {},
        couponList: [],
        couponAmout: '',
        toPayAmount: '',
        useCoupon: true,
        couponListLen: '',
        tabs: ["商家配送", "到店消费"],
        activeIndex: 0,
        sliderOffset: 0,
        sliderLeft: 0,
        sliderWidth,
        userCard: [],
        userCardNames: [],
        cardIndex: 0,
        rmPostAmount: '',
        couponId: '',
        optionAddrId: '',
        isOutAddress: 0
    },
    /**
     * 页面加载
     */
    onLoad: function(options) {
        var _self = this;
        var toData = {
            goodsId: JSON.parse(options.goodsId),
            skuId: JSON.parse(options.skuId),
            amount: JSON.parse(options.amount),
            cartId: options.cartId || 0,
            shop: app.getShop(),
            deskNum: options.deskNum
        };

        this._options = options;
        _self._actId = options.actId;
        _self._actType = options.actType;
        _self._groupBuyId = options.groupBuyId;
        _self._deskNum = options.deskNum;
        if (options.deskNum) {
            toData.activeIndex = 1;
        }
        // if (options.addressId) {
        //     toData.addressId = options.addressId;
        // }
        this.setData(toData);
        this._initTabs();
    },
    onShow: function() {
        var optionAddrId = this.data.optionAddrId;
        if (optionAddrId) {
            this._resetAddr(optionAddrId);
            this.getPostage(optionAddrId);
        } else {
            this.showSalt();
        }
    },
    _initTabs() {
        var that = this;
        wx.getSystemInfo({
            success: function(res) {
                that.setData({
                    sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
                    sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
                });
            }
        });
    },
    /**
     * 切换到店或者外卖下单
     */
    tabClick: function(e) {
        var formId = e.detail.formId;
        var oldIndex = this.data.activeIndex;
        var curIndex = e.currentTarget.id;
        var orderId = this.data.orderId;
        var orderAmount = parseFloat(this._orderAmount);
        var couponAmout = this.data.couponAmout;
        var toPayAmount = this.data.toPayAmount;
        var coupon = this.data.coupon;
        var postage = parseFloat(this.data.postage);
        var cardIndex = this.data.cardIndex;
        var userCard = this.data.userCard;
        var rmPostAmount = this.data.rmPostAmount;


        if (oldIndex == curIndex) {
            return;
        }
        if (orderId) {
            return util.alert('订单已生成，不能修改消费方式，您可以重新下单');
        }


        if (cardIndex == 0) {
            if (this.data.coupon.length == 0) {
                toPayAmount = orderAmount;
            } else {
                couponAmout = !couponAmout ? parseFloat(this.data.coupon.coupon_amount).toFixed(2) || 0 : couponAmout;
                toPayAmount = orderAmount - couponAmout;
            }


            toPayAmount = curIndex == 1 ? (toPayAmount - postage).toFixed(2) : toPayAmount.toFixed(2);
            rmPostAmount = orderAmount;

            /*
            ** 这个是第一版写的,优化的目的是为了,尽可能少的setData
            ***
             this.setData({
                 sliderOffset: e.currentTarget.offsetLeft,
                 activeIndex: curIndex,
                 orderAmount: curIndex == 1 ? (orderAmount - postage).toFixed(2) : orderAmount.toFixed(2),
                 toPayAmount: curIndex == 1 ? (toPayAmount - postage).toFixed(2) : toPayAmount.toFixed(2),
                 rmPostAmount: orderAmount
             });
            **/
        } else {
            toPayAmount = curIndex == 1 ? ((orderAmount - postage) * userCard[cardIndex - 1].discount / 10).toFixed(2) : ((orderAmount - postage) * userCard[cardIndex - 1].discount / 10 - (-postage)).toFixed(2);
            rmPostAmount = (orderAmount - postage).toFixed(2);

            /*
            ** 这个是第一版写的,优化的目的是为了,尽可能少的setData
            ***
             this.setData({
                 sliderOffset: e.currentTarget.offsetLeft,
                 activeIndex: curIndex,
                 orderAmount: curIndex == 1 ? (orderAmount - postage).toFixed(2) : orderAmount.toFixed(2),
                 toPayAmount: curIndex == 1 ? ((orderAmount - postage) * userCard[cardIndex - 1].discount / 10).toFixed(2) : ((orderAmount - postage) * userCard[cardIndex - 1].discount / 10 - (-postage)).toFixed(2),
                 rmPostAmount: (orderAmount - postage).toFixed(2)
             });
            **/
        }

        orderAmount = curIndex == 1 ? (orderAmount - postage).toFixed(2) : orderAmount.toFixed(2);

        this.setData({
            sliderOffset: e.currentTarget.offsetLeft,
            activeIndex: curIndex,
            orderAmount,
            toPayAmount,
            rmPostAmount
        })
        common.submitForm(formId);
    },

    /**
     * 页面初始化数据
     */
    showSalt: function() {
        var $this = this;
        var goodsId = this.data.goodsId;
        var skuId = this.data.skuId;
        var amount = this.data.amount;
        var ajaxUrl = '/openapi/CHome/showQuickBuy';
        var ajaxParams = {
            goodsId: goodsId,
            skuId: skuId,
            amount: amount,
            act_id: $this._actId,
            act_type: $this._actType
        };

        ajax.P(ajaxUrl, ajaxParams, function(data) {
                var result = data.result;
                var postage = parseFloat(result.postage); //邮费
                var orderAmount = parseFloat(result.orderAmount); //订单金额
                var toPayAmount = parseFloat(result.toPayAmount); //应付款
                var userCard = result.userCard; //是否可以使用会员卡支付
                var isOutAddress = result.isOutAddress;
                var userCardNames = [];
                userCardNames.push('微信支付');
                if (userCard.length > 0) {
                    userCard.forEach(function(item) {
                        userCardNames.push(item.card_name);
                    })
                }

                shopInfo.init('shopInfoData', $this);
                $this._orderAmount = orderAmount;
                $this._toPayAmount = toPayAmount;
                $this._couponCode = result.couponCode;

                //result.address 为空的时候是数组格式，不为空的时候是json格式
                if (result.address.length != 0) {
                    $this._noAddr = false;
                } else {
                    $this._noAddr = true;
                }

                $this.setData({
                    orderType: result.orderType,
                    address: result.address,
                    addressId: result.address.id || '',
                    coupon: result.coupon,
                    goodsList: result.goodsList,
                    orderAmount: orderAmount.toFixed(2),
                    toPayAmount: toPayAmount.toFixed(2),
                    postage: postage.toFixed(2),
                    dataLoaded: true,
                    userCard: userCard,
                    userCardNames: userCardNames,
                    noAddr: $this._noAddr,
                    isOutAddress: isOutAddress
                });

                $this._getCouponList($this._couponCode);
            }

        );

    },
    /**
     * 微信支付
     */
    skip: function(e) {
        var formId = e.detail.formId;
        this.confirmGoods();
        common.submitForm(formId);
    },
    /**
     * 会员卡支付
     */
    _cartPaySkip: function(e) {
        var _self = this;
        var formId = e.detail.formId;
        util.confirm('确认支付', function() {
            _self.confirmGoods();
        });
        common.submitForm(formId);
    },
    _remark: function(e) {
        var remark = e.detail.value;
        this._remarkValue = remark;
    },
    /**
     *支付 
     */
    confirmGoods: function() {
        var {
            activeIndex,
            addressId,
            goodsId,
            skuId,
            amount,
            cartId,
            orderId,
            orderType,
            coupon,
            cardIndex,
            userCard,
            couponId,
            isOutAddress
        } = this.data;

        var actId = this._actId;
        var actType = this._actType;
        var cid = 0;
        var pay_type = 2;
        var recommend = app.getRecommend() || 0;
        var $this = this;
        var ajaxUrl,
            ajaxParams;

        couponId = couponId ? couponId : coupon.id || '';

        if (cardIndex > 0) {
            cid = userCard[cardIndex - 1].cid;
            pay_type = 3;
        }


        if (orderId) {
            this._payAgain();
            return;
        }

        if (activeIndex == 0) {
            if (addressId && isOutAddress == 1){
                    util.alert('配送地址超出商家配送范围');
                    return false;
            }

        }

        if (orderType == 5) {
            if (activeIndex == 0) { //配送订单
                orderType = 3;
            } else if (activeIndex == 1) { //到店消费
                orderType = 2;
            }
        }

        ajaxUrl = '/openapi/CHome/quickOrder';
        ajaxParams = {
            openId: app.getOpenId(),
            goods_id: goodsId,
            address_id: addressId,
            pay_type: pay_type,
            is_cash: 0,
            sku_id: skuId,
            amount: amount,
            order_type: orderType,
            cartId: cartId,
            coupon_id: couponId,
            recommend: recommend,
            cid: cid,
            act_id: $this._actId,
            act_type: $this._actType,
            remark: $this._remarkValue || ''
        };

        if ($this._deskNum) {
            ajaxParams.deskNum = $this._deskNum;
        }

        if (actType && actType == 1) { //团购
            ajaxUrl = '/openapi/CActivity/groupBuyQuickOrder';
            ajaxParams.group_buy_id = this._groupBuyId;
        }

        ajax.P(ajaxUrl, ajaxParams, function(data) {
            var result = data.result;
            var {
                orderId,
                groupById: groupBuyId
            } = result;

            $this._groupBuyId = groupBuyId;
            $this.setData({
                orderId,
            });

            if (pay_type == 2) {
                var wxPayParams = JSON.parse(data.result.wxPayParams);
                $this._package = wxPayParams.package;
                var prepayArr = $this._package.split('=');
                common.submitPrepay(prepayArr[1]);
                $this._paySuccess(wxPayParams);
            } else if (pay_type == 3) {
                util.showOK('支付成功', function() {
                    wx.redirectTo({
                        url: '../orderList/orderList?ty=1'
                    });
                });
            }
        })
    },

    /**
     * 再次支付
     */
    _payAgain() {
        var $this = this;
        var activeIndex = this.data.activeIndex;
        var addressId = this.data.addressId;
        var orderType = this.data.orderType;
        var params = {
            openId: app.getOpenId(),
            orderId: this.data.orderId,
        };

        if (orderType == 5) {
            if (activeIndex == 0) { //配送订单
                orderType = 3;
            } else if (activeIndex == 1) { //到店消费
                orderType = 2;
            }
        }
        params.order_type = orderType;

        if (orderType == 3) {
            params.address_id = addressId;
        }

        var url = '/openapi/CHome/doPayAgain';

        if ($this._actType == 1) { //团购
            url = '/openapi/CActivity/doPayAgain';
        }
        ajax.P(url, params, function(data) {
            var result = data.result;
            $this._paySuccess(JSON.parse(result.wxPayParams));
        })
    },

    /**
     * 支付成功回调
     */
    _paySuccess(wxPayParams) {
        var _self = this;
        var userCardNames = _self.data.userCardNames;
        _self.setData({
            userCardNames: userCardNames.slice(0, 1)
        })
        wxPayParams.success = function() {
            var url = '/pages/orderList/orderList?ty=1';
            if (_self._actId && _self._actType == 1) { //团购
                url = '/pages/groupBuyInfo/index?actId=' + _self._actId + '&groupBuyId=' + _self._groupBuyId;
            }
            wx.redirectTo({
                url
            });
        }
        wxUtil.wxPay(wxPayParams);
    },
    /**
     * 选择地址
     */
    _goToAddr: function(e) {
        var formId = e.detail.formId;
        var orderId = this.data.orderId;
        if (orderId) {
            return util.alert('订单已生成，不能修改地址信息');
        }

        /*
        ** 这个是第一版写的,优化的目的是因为页面来回跳转带参数，实在感觉不好。所以换成了在跳转到的页面重新设置上一个页面的参数(比如:A->B,在B页面把B的数据付给A页面。用到的api:getCurrentPages())
        ***
        // var optionsStr = JSON.stringify(this._options);
        // if (!this.data.noAddr) {
        //     wx.navigateTo({
        //         url: '/pages/myAddr/myAddr?orderOptions=' + optionsStr,
        //     })
        // } else {
        //     wx.navigateTo({
        //         url: '/pages/selectedAddr/selectedAddr?orderOptions=' + optionsStr,
        //     })
        // }
        **/

        if (!this.data.noAddr) {
            wx.navigateTo({
                url: '/pages/myAddr/myAddr',
            })
        } else {
            wx.navigateTo({
                url: '/pages/selectedAddr/selectedAddr',
            })
        }
        common.submitForm(formId);
    },
    /**
     * 切换优惠券列表
     */
    _toggleCouponsList(e) {
        var formId = e.detail.formId;
        this.setData({
            showDialog: !this.data.showDialog
        });
        if (typeof(formId) != "undefined") {
            common.submitForm(formId);
        }
    },
    /**
     * 加载优惠券列表
     */
    _getCouponList: function(couponCode, cb) {
        var self = this;
        var url = '/openapi/CCoupon/getOrderCouponList';
        ajax.P(url, {
            couponCode: couponCode
        }, function(data) {
            var couponList = data.result.list || [];
            var couponListLen = +data.result.list.length;
            var coupon = self.data.coupon;
            var toData = {
                couponList: couponList,
                couponListLen: couponListLen
            };
            var couponList = toData.couponList;
            if (data.result.list.length > 0) {
                couponList.forEach(function(item, index) {
                    item.value = index;
                    if (item.id == coupon.id) {
                        item.checked = true;
                    }
                });
            }
            self.setData(toData);
            cb && cb();
        });
    },
    /**
     * 选择优惠券或原价支付
     */
    _switch1Change: function(e) {
        var couponList = this.data.couponList;
        var orderAmount = this.data.orderAmount;
        var couponAmout = this.data.couponAmout;
        var toPayAmount = this.data.toPayAmount;
        var useCoupon = this.data.useCoupon;
        var couponId = this.data.couponId;
        var _self = this;
        this._useCoupon = !useCoupon;
        if (!this._useCoupon) {
            couponList.some(function(item, index) {
                if (couponList[index].checked) {
                    couponList[index].checked = false;
                    _self._index = index;
                }
            })
            couponId = '0';
            couponAmout = parseFloat(0).toFixed(2);
            toPayAmount = orderAmount;
        } else {
            couponList.some(function(item, index) {
                couponList[_self._index].checked = true;
                couponId = couponList[_self._index].id;
                couponAmout = parseFloat(couponList[_self._index].coupon_amount).toFixed(2);
            })

            toPayAmount = (orderAmount - couponAmout).toFixed(2);
        }
        this.setData({
            couponId,
            couponAmout,
            toPayAmount,
            couponList,
            useCoupon: this._useCoupon
        });
    },
    /**
     * 切换支付方式(微信支付或会员卡)
     */
    _bindSelectPayMode: function(e) {

        var formId = e.detail.formId;
        var orderId = this.data.orderId;
        var couponList = this.data.couponList;
        var cardIndex = this.data.cardIndex;
        var userCardNames = this.data.userCardNames;
        var orderAmount = this.data.orderAmount;
        var toPayAmount = this.data.toPayAmount;
        var couponAmout = this.data.couponAmout;
        var userCard = this.data.userCard;
        var orderType = this.data.orderType;
        var activeIndex = this.data.activeIndex;
        var postage = this.data.postage;
        var rmPostAmount = this.data.rmPostAmount;

        if (orderId) {
            return util.alert('订单已生成，不能修改支付方式!');
        }

        cardIndex = e.currentTarget.dataset.value;

        if (cardIndex == 0) {
            if (this.data.coupon.length == 0) {
                toPayAmount = orderAmount;
            } else {
                couponAmout = !couponAmout ? parseFloat(this.data.coupon.coupon_amount).toFixed(2) || 0 : couponAmout;
                toPayAmount = (orderAmount - couponAmout).toFixed(2);
            }

            /*
            ** 这个是第一版写的,优化的目的是为了,尽可能少的setData
            ***
             this.setData({
                 couponAmout: couponAmout,
                 toPayAmount: toPayAmount
             });
            **/

        } else {
            //这个最初的目的是要在页面中添加会员卡的。。这个变量是给会员卡编号前面补‘0’用的(类似:00006);
            // userCard[cardIndex-1]['cid'] = this.PrefixInteger(userCard[cardIndex-1]['cid'],6);
            if (orderType == 3 || (orderType == 5 && activeIndex == 0)) {
                rmPostAmount = orderAmount - postage;
                if (userCard[cardIndex - 1].discount < 10) {
                    toPayAmount = (orderAmount - postage) * userCard[cardIndex - 1].discount / 10 - (-postage);
                } else {
                    toPayAmount = orderAmount;
                }
            } else {
                if (userCard[cardIndex - 1].discount < 10) {
                    toPayAmount = orderAmount * userCard[cardIndex - 1].discount / 10;
                } else {
                    toPayAmount = orderAmount;
                }
            }
            rmPostAmount = parseFloat(rmPostAmount).toFixed(2);
            toPayAmount = parseFloat(toPayAmount).toFixed(2);

            /*
            ** 这个是第一版的,优化的目的是为了,尽可能少的setData
            ***
             this.setData({
                 rmPostAmount: parseFloat(rmPostAmount).toFixed(2),
                 toPayAmount: parseFloat(toPayAmount).toFixed(2)
             })
            **/

        }
        this.setData({
            cardIndex,
            couponAmout,
            toPayAmount,
            rmPostAmount
        })
        common.submitForm(formId);
    },
    /**
     * 从地址选择页面后，回来重新更新地址块
     */
    _resetAddr: function(addressId) {
        var _self = this;
        ajax.G('/openapi/CAddress/getAddrById', {
                id: addressId
            },
            function(data) {
                var result = data.result;
                var address = {};

                //result 有值的时候返回 json格式，无值的时候返回array格式
                if (result.length != 0) {
                    address.re_name = result.re_name;
                    address.re_phone = result.re_phone;
                    address.fullAddr = result.province_name + result.city_name + result.district_name + result.detail_addr;
                    address.is_default = result.is_default;
                    addressId = result.id;
                    _self.setData({
                        address,
                        addressId,
                        noAddr: false
                    })
                } else {
                    _self.showSalt();
                }
            }
        )
    },
    /**
     * 选择优惠券
     */
    radioChange: function(e) {
        var _self = this;
        var couponList = this.data.couponList;
        var couponAmout = this.data.couponAmout;
        var orderAmount = this.data.orderAmount;
        var toPayAmount = this.data.toPayAmount;
        var couponId = this.data.couponId;
        couponList.some(function(item, index) {
            couponList[index].checked = couponList[index].value == e.detail.value;
            if (couponList[index].checked) {
                couponId = couponList[index].id;
                couponAmout = parseFloat(couponList[index].coupon_amount).toFixed(2);
                toPayAmount = (orderAmount - couponAmout).toFixed(2);
            }
        })
        this.setData({
            couponId,
            couponAmout,
            toPayAmount,
            couponList
        });
    },
    _jump: function(evt) {
        common.jump(evt);
    },
    getPostage: function(addrId) {
        var url = '/openapi/CHome/getPostage';

        var orderAmount = this.data.orderAmount;
        var toPayAmount = this.data.toPayAmount;
        var oldPostage = this.data.postage;
        var orderType = this.data.orderType;
        var activeIndex = this.data.activeIndex;

        if (orderType == 5) {
            if (activeIndex == 0) { //配送订单
                orderType = 3;
            } else if (activeIndex == 1) { //到店消费
                orderType = 2;
            }
        }

        var paramsData = {
            orderAmount,
            addrId,
            orderType
        }
        ajax.P(url, paramsData, (data) => {
            var data = data.result;
            var newPostage = data.postage;
            orderAmount = (parseFloat(orderAmount) - parseFloat(oldPostage) + parseFloat(newPostage)).toFixed(2);
            toPayAmount = (parseFloat(toPayAmount) - parseFloat(oldPostage) + parseFloat(newPostage)).toFixed(2);
            this._orderAmount = orderAmount;
            this.setData({
                postage: parseFloat(data.postage).toFixed(2),
                isOutAddress: data.isOutAddress,
                orderAmount,
                toPayAmount
            })
        })
    }
    /**
    * 给会员卡编号补0
    PrefixInteger: function(num, length) {
        return (Array(length).join('0') + num).slice(-length);
    }
    */
}));